package com.cjy.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.cjy.pojo.*;
import com.cjy.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;
    
    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    @Autowired
    private UserService userService;

    @Autowired
    private HttpSession session;

    @Autowired
    private ThumbUpService thumbUpService;

    @Value("${fastdfs_domaint}")
    private String fastdfsDomaint;


    private final Logger logger = (Logger) LoggerFactory.getLogger(this.getClass());

    /**
     * 前端首页
     */
    @GetMapping("/")
    public String index(@PageableDefault(size = 8,sort = {"createTime"},direction = Sort.Direction.DESC)
                                    Pageable pageable, Model model){
        List<Type> types = typeService.listTypeTop(6);
        List<Type> collect = types.stream().map(data -> {
            Type type = new Type();
            type.setId(data.getId());
            type.setName(data.getName());
            type.setCountBlog(blogService.blogCountByType(data.getId()));
            return type;
        }).collect(Collectors.toList());
        List<Tag> tags = tagService.listTagTop(10);
        List<Tag> collectTags = tags.stream().map(data -> {
            Tag tag = new Tag();
            tag.setId(data.getId());
            tag.setName(data.getName());
            List<Blog> blogs = getCountTag(data.getBlogs());
            tag.setCountTag(blogs.size());
            return tag;
        }).collect(Collectors.toList());
        Page<Blog> blogs = blogService.listBlog(pageable);
        User user = (User) session.getAttribute("user");
        Long userId = -1L;
        if (ObjectUtil.isNotNull(user)) {
            userId = user.getId();
        }

        List<Long> blogIds = thumbUpService.getThumbUpByUid(userId)
                .stream().filter(e->{
            e.getCancel();
            return !e.getCancel();
        }).collect(Collectors.toList()).stream().map(e -> {
            e.getCancel();
            return e.getBlogId();
        }).collect(Collectors.toList());

        List<Blog> blogList = blogs.getContent().stream().map(e -> {
            e.setThumbUp(blogIds.contains(e.getId()));
            User user1 = e.getUser();
            user1.setRealAvatar(fastdfsDomaint + user1.getAvatar());
            e.setUser(user1);
            return e;
        }).collect(Collectors.toList());
        model.addAttribute("page",blogs);
        model.addAttribute("content",blogList);
        model.addAttribute("types", collect);
        model.addAttribute("tags", collectTags);
        model.addAttribute("recommendBlogs",blogService.listBlogTop(8));
        return "index";
    }

    public List<Blog> getCountTag(List<Blog> data) {
        return data.stream().filter(res -> (res.isRecommend() && res.isPublished() && res.getStatus() == 1)).collect(Collectors.toList());
    }

    /**
     * 分类页面
     */
    @GetMapping("/type")
    public String type(@PageableDefault(size = 8,sort = {"updateTime"},direction = Sort.Direction.DESC)
                                Pageable pageable, Model model){
        List<Type> types = typeService.listType();
        List<Type> types1 = typeService.listTypeTop(types.size());
        List<Type> collect = types1.stream().map(data -> {
            Type type = new Type();
            type.setId(data.getId());
            type.setName(data.getName());
            type.setCountBlog(blogService.blogCountByType(data.getId()));
            return type;
        }).collect(Collectors.toList());
        Long typeId = types1.get(0).getId();
        Page<Blog> blogPage = blogService.listBlogByTypeId(typeId, pageable);
        List<Blog> blogs = blogPage.getContent().stream().map(e -> {
            User user = e.getUser();
            user.setRealAvatar(fastdfsDomaint + user.getAvatar());
            e.setUser(user);
            return e;
        }).collect(Collectors.toList());
        model.addAttribute("blogs",blogs);
        model.addAttribute("types",collect);
        model.addAttribute("typesId",typeId);
        model.addAttribute("page",blogPage);
        return "type";
    }

    @GetMapping("/type/{id}")
    public String typeById(@PageableDefault(size = 8,sort = {"updateTime"},direction = Sort.Direction.DESC)
                               Pageable pageable,@PathVariable Long id, Model model){
        List<Type> types = typeService.listType();
        List<Type> types1 = typeService.listTypeTop(types.size());
        List<Type> collect = types1.stream().map(data -> {
            Type type = new Type();
            type.setId(data.getId());
            type.setName(data.getName());
            type.setCountBlog(blogService.blogCountByType(data.getId()));
            return type;
        }).collect(Collectors.toList());
        Page<Blog> blogPage = blogService.listBlogByTypeId(id, pageable);
        List<Blog> blogs = blogPage.getContent().stream().map(e -> {
            User user = e.getUser();
            user.setRealAvatar(fastdfsDomaint + user.getAvatar());
            e.setUser(user);
            return e;
        }).collect(Collectors.toList());
        model.addAttribute("blogs",blogs);
        model.addAttribute("types",collect);
        model.addAttribute("typesId",id);
        model.addAttribute("page",blogPage);
        return "type";
    }

//    @ResponseBody
//    @RequestMapping("/test")
//    public String test(@RequestParam("id") Long id,
//                       @PageableDefault(size = 8,sort = {"updateTime"},direction = Sort.Direction.DESC)
//                               Pageable pageable){
//        Page<Blog> blogs = blogService.listBlogByTagId(id, pageable);
//        String s = JSON.toJSONString(blogs);
//        System.out.println(s);
//        return s;
//    }

    @GetMapping("/tags")
    public String tag(@PageableDefault(size = 8,sort = {"updateTime"},direction = Sort.Direction.DESC)
                               Pageable pageable, Model model){
        List<Tag> tags = tagService.listTag();
        List<Tag> tags1 = tagService.listTagTop(tags.size());
        List<Tag> collectTags = tags1.stream().map(data -> {
            Tag tag = new Tag();
            tag.setId(data.getId());
            tag.setName(data.getName());
            List<Blog> blogs = getCountTag(data.getBlogs());
            tag.setCountTag(blogs.size());
            return tag;
        }).collect(Collectors.toList());
        Long tagId = tags1.get(0).getId();
        Page<Blog> blogPage = blogService.listBlogByTagId(tagId, pageable);
        List<Blog> blogs = blogPage.getContent().stream().map(e -> {
            User user = e.getUser();
            user.setRealAvatar(fastdfsDomaint + user.getAvatar());
            e.setUser(user);
            return e;
        }).collect(Collectors.toList());
        model.addAttribute("blogs",blogs);
        model.addAttribute("tags",collectTags);
        model.addAttribute("tagId",tagId);
        model.addAttribute("page",blogPage);
        return "tags";
    }

    @GetMapping("/tags/{id}")
    public String tag(@PageableDefault(size = 8,sort = {"updateTime"},direction = Sort.Direction.DESC)
                              Pageable pageable,@PathVariable Long id, Model model){
        List<Tag> tags = tagService.listTag();
        List<Tag> tags1 = tagService.listTagTop(tags.size());
        List<Tag> collectTags = tags1.stream().map(data -> {
            Tag tag = new Tag();
            tag.setId(data.getId());
            tag.setName(data.getName());
            List<Blog> blogs = getCountTag(data.getBlogs());
            tag.setCountTag(blogs.size());
            return tag;
        }).collect(Collectors.toList());
        Page<Blog> blogPage = blogService.listBlogByTagId(id, pageable);
        List<Blog> blogs = blogPage.getContent().stream().map(e -> {
            User user = e.getUser();
            user.setRealAvatar(fastdfsDomaint + user.getAvatar());
            e.setUser(user);
            return e;
        }).collect(Collectors.toList());
        model.addAttribute("blogs",blogs);
        model.addAttribute("page",blogPage);
        model.addAttribute("tags",collectTags);
        model.addAttribute("tagId",id);
        return "tags";
    }


    @PostMapping("/search")
    public String search(@PageableDefault(size = 8,sort = {"updateTime"},direction = Sort.Direction.DESC)
            Pageable pageable, Model model,@RequestParam("query") String query){
        model.addAttribute("page", blogService.listBlogSearch(query,pageable));
        model.addAttribute("query",query);
        return "search";
    }

    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id,Model model){
        blogService.updateBlogViews(id);
        Blog blog = blogService.getBlog(id);
        User user = blog.getUser();
        user.setRealAvatar(fastdfsDomaint + user.getAvatar());
        blog.setUser(user);
        model.addAttribute("blog",blogService.getAndConvert(blog));
        model.addAttribute("header",fastdfsDomaint);
        return "blog";
    }

    @GetMapping("infoMe")
    public String infoMe(Model model){
        model.addAttribute("description",userService.showUserDescription());
        model.addAttribute("types",typeService.listTypeTop(8));
        model.addAttribute("tags",tagService.listTagTop(8));
        return "infoMe";
    }

    /**
     * 点赞和取消点赞的实现
     */
    @GetMapping("/thumbUp/{blogId}")
    public String thumbUpByUser (@PathVariable Long blogId){
        thumbUpService.updateThumbup(blogId);
        return "redirect:/";
    }



}
